import React, { useEffect, useState } from 'react'
import { useUserStore, useRouteStore } from '@/store'
import { Navigate, useLocation } from 'react-router'
import { Spin } from 'antd'

// 路径白名单
const WHITE_LIST = ['/login', '/test']

export default function AuthRoute({ children }) {
  const { token, getUserInfo, userInfo } = useUserStore()
  const { filterRoutes } = useRouteStore()
  const location = useLocation()
  const path = location.pathname
  const [loading, setLoading] = useState(true)
  const [valid, setValid] = useState(false)

  // 白名单路径直接访问
  if (WHITE_LIST.includes(path)) {
    return children
  }
  useEffect(() => {
    let fetchData = async function(){
      console.log('fetchData')
      try {
        if (!token) return
        setLoading(true)
        // 获取用户信息和权限路由信息
        await getUserInfo()
        await filterRoutes()
        setLoading(false)
        setValid(true)
      } catch(error) {
        console.error(error)
        setLoading(false)
        setValid(false)
      }
    }
    if(!(userInfo && userInfo.userId)){
      fetchData()
    }
  }, [token])

  if (!token) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
        <Spin tip="加载中..." size="large" fullscreen/>
      </div>
    )
  }

  if (!valid) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  return children
}
